package com.heima.media.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.media.entity.WmSensitive;
import com.heima.media.service.IWmSensitiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author: itheima
 * @create: 2022-05-18 15:10
 */
@RestController
@RequestMapping("/test")
public class TestController {


    @Autowired
    private IWmSensitiveService wmSensitiveService;

    /**
     * 导入Excel文件中敏感词
     * TODO： 1.改为文件上传    2.参考官方文档数据监听器方式：分批次导入
     * @param filename
     * @return
     */
    @PostMapping("/read")
    public ResponseResult readExcel(String filename) {
        EasyExcel.read(filename, WmSensitive.class, new PageReadListener<WmSensitive>(dataList -> {
            /**
             * 读取到是Excel文件中一行行记录
             */
            for (WmSensitive sensitive : dataList) {
                //查询敏感词是否存在 如果不存在则新增
                LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmSensitive::getSensitives, sensitive.getSensitives());
                int count = wmSensitiveService.count(queryWrapper);
                if (count == 0) {
                    sensitive.setCreatedTime(new Date());
                    wmSensitiveService.save(sensitive);
                } else {
                    sensitive.setCreatedTime(new Date());
                    wmSensitiveService.updateById(sensitive);
                }
            }
        })).sheet().doRead();
        return ResponseResult.okResult();
    }



    /**
     * 读取数据库写入到excel中
     * TODO：将写入文件下载到本地
     * @param fileName
     * @return
     */
    @PostMapping("/write")
    public ResponseResult writeExcel(String fileName){
        // 从数据库查询敏感词列表
        List<WmSensitive> list = wmSensitiveService.list();
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, WmSensitive.class)
                .sheet("敏感词")
                .doWrite(() -> {
                    // 分页查询数据
                    return list;
                });
        return ResponseResult.okResult();
    }
}
